﻿app.factory('NoteFactory', ['$http', '$q', function ($http, $q) {
    var notes = [];

    var getAllNotes = function () {
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: '',
            contentType: 'application/json'
        }).success(function (data) {
            deferred.resolve(data);
        }).error(function (data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    var createMovie = function (movie) {
        var deferred = $q.defer();
        $http({
            method: 'POST',
            url: '',
            data: movie,
            contentType: 'application/json'
        }).success(function (data) {
            movie.MovieId = data;
            movies.push(movie);
            deferred.resolve();
        }).error(function (data) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    var deleteNote = function (id) {
        var deferred = $q.defer();
        $http({
            method: 'DELETE',
            url: '' + id
        }).success(function (data) {
            for (var i = 0; i < notes.length; i++) {
                if (Notes[i].NoteId == id) {
                    Notes.splice(i, 1);
                    break;
                }
            }
            deferred.resolve(data);
        }).error(function (data) {
            deferred.reject(data);
        });
        return deferred.promise;
    }
    getAllNotes().then(function (data) {
        for (var i = 0; i < data.length; i++) {
            notes.push(data[i]);
        }
    });

    return {
        notes: notes,
        createNotes: createNotes,
        deleteNotes: deleteNotes
    }
}]);
